package cn.labbook.bluetooth.controller;

import cn.labbook.bluetooth.common.ResultDto;
import cn.labbook.bluetooth.common.TokenManager;
import cn.labbook.bluetooth.constant.AdminConstant;
import cn.labbook.bluetooth.constant.AmmeterConstant;
import cn.labbook.bluetooth.constant.PrivilegeConstant;
import cn.labbook.bluetooth.entity.*;
import cn.labbook.bluetooth.service.*;
import cn.labbook.bluetooth.util.CollectionUtils;
import cn.labbook.bluetooth.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class IndexController extends AbstractController {

    @Autowired
    IResourceService resourceService;
    @Autowired
    IAdminResService adminResService;
    @Autowired
    IServicePayCreateService servicePayCreateService;
    @Autowired
    IAdminService adminService;
    @Autowired
    IServicePayService servicePayService;
    @Autowired
    IAmmeterService ammeterService;
    @Autowired
    IConstantService constantService;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

//    @RequestMapping(value = "logout", method = RequestMethod.GET)
//    public String logout() {
//        // 使用权限管理工具进行用户的退出，注销登录
//        SecurityUtils.getSubject().logout(); // session
//        // 会销毁，在SessionListener监听session销毁，清理权限缓存
//        return "redirect:login";
//    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        List<Resource> resourceslist = new ArrayList<>();
        LambdaQueryWrapper<AdminRes> lambda = new QueryWrapper<AdminRes>().lambda();
        lambda.eq(AdminRes::getAdminId, TokenManager.getToken().getAdminId());
        adminResService.list(lambda).forEach(adminRes -> {
            LambdaQueryWrapper<Resource> lambd = new QueryWrapper<Resource>().lambda();
            lambd.eq(Resource::getResourceId, adminRes.getResourceId());
            if (resourceService.getOne(lambd).getResourceType() == 2) {
                resourceslist.add(resourceService.getOne(lambd));
            }
        });
        if (CollectionUtils.isNotEmpty(resourceslist)) {
            model.addAttribute("privileges", resourceslist);
            model.addAttribute("admin", TokenManager.getToken().getAdmin());
            model.addAttribute("adminName", TokenManager.getToken().getAdminName());
            String[] i;
            Map<String, Double> stringDoubleMap = null;
            LambdaQueryWrapper<Ammeter> lambda1 = new QueryWrapper<Ammeter>().lambda();
            lambda1.eq(Ammeter::getStatus, AmmeterConstant.ACTIVATE);
            LambdaQueryWrapper<Ammeter> lambda2 = new QueryWrapper<Ammeter>().lambda();
            lambda2.eq(Ammeter::getStatus, AmmeterConstant.NOTACTIVATE);

            if (TokenManager.getToken().getAdmin().getAdminStatus() == AdminConstant.position.ZK) {
                i = servicePayService.servicePayStatisticsForArray();
                stringDoubleMap = servicePayService.servicePayEachStatistics();
            } else if (TokenManager.getToken().getAdmin().getAdminStatus() == AdminConstant.position.MANUFACTURERS) {
                i = null;
                lambda1.eq(Ammeter::getManufacturersId, TokenManager.getToken().getAdminId());
                lambda2.eq(Ammeter::getManufacturersId, TokenManager.getToken().getAdminId());
            } else if (TokenManager.getToken().getAdmin().getAdminStatus() == AdminConstant.position.DEALER) {
                i = servicePayService.servicePayStatisticsByAdminForArray();
                stringDoubleMap = servicePayService.servicePayEachStatisticsByAdmin();
                lambda1.eq(Ammeter::getAdminId, TokenManager.getToken().getAdminId());
                lambda2.eq(Ammeter::getAdminId, TokenManager.getToken().getAdminId());
            } else {
                i = null;
                lambda1.eq(Ammeter::getManagerId, TokenManager.getToken().getAdminId());
                lambda2.eq(Ammeter::getManagerId, TokenManager.getToken().getAdminId());
            }
            if (i != null && i.length != 0) {
                model.addAttribute("dataArr", JSONObject.toJSONString(i));
            }
//            LambdaQueryWrapper<Ammeter> lambda1 = new QueryWrapper<Ammeter>().lambda();
//            lambda1.eq(Ammeter::getStatus, AmmeterConstant.ACTIVATE);
//            LambdaQueryWrapper<Ammeter> lambda2 = new QueryWrapper<Ammeter>().lambda();
//            lambda2.eq(Ammeter::getStatus, AmmeterConstant.NOTACTIVATE);
//            if(TokenManager.getToken().getAdmin().getAdminStatus()== AdminConstant.position.MANUFACTURERS){
//                lambda1.eq(Ammeter::getManufacturersId,TokenManager.getToken().getAdminId());
//                lambda2.eq(Ammeter::getManufacturersId,TokenManager.getToken().getAdminId());
//            }
//            if(TokenManager.getToken().getAdmin().getAdminStatus()== AdminConstant.position.DEALER){
//                lambda1.eq(Ammeter::getManagerId,TokenManager.getToken().getAdminId());
//                lambda2.eq(Ammeter::getManagerId,TokenManager.getToken().getAdminId());
//            }
            model.addAttribute("activate", ammeterService.count(lambda1));
            model.addAttribute("notactivate", ammeterService.count(lambda2));
            model.addAttribute("stringDoubleMap", stringDoubleMap);
            return "index";
        }

        return "login";
    }

    @RequestMapping("/admin")
    public String user() {
        return "admin";
    }

    @RequestMapping("/ammeters")
    public String ammeters() {
        return "ammeters";
    }

    @RequestMapping("/adminAmmeters")
    public String adminAmmeters() {
        return "adminAmmeters";
    }

    @RequestMapping("/zkAmmeters")
    public String zkAmmeters() {
        return "zkAmmeters";
    }

    @RequestMapping("/ammeterStatistics")
    public String ammeterStatistics() {
        return "ammeterStatistics";
    }

    @RequestMapping("/landlordList")
    public String landlordList() {
        return "landlordList";
    }

    @RequestMapping("/recharge")
    public String recharge() {
        return "recharge";
    }

    @RequestMapping({"/rechargeList"})
    public String rechargeList() {
        return "rechargeList";
    }

    @RequestMapping({"/transferList"})
    public String transferList(){return "transferList";}

    @RequestMapping("/dealer")
    public String dealer() {
        return "dealer";
    }

    @RequestMapping("/managerInfo")
    public String managerInfo() {
        return "managerInfo";
    }

    @RequestMapping("/ammeter/reading")
    public String ammeterReading() {
        return "ammeterReading";
    }

    @RequestMapping("/pay")
    @ResponseBody
    public ResultDto pay(String serverData) {
        JSONArray objects = JSONArray.parseArray(serverData);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSS");//设置日期格式
        String date = df.format(new Date());
//        Double payPrice = adminService.getById(TokenManager.getToken().getAdminId()).getPayPrice();
        double payALlPrice = 0;
        for (int i = 0; i < objects.size(); i++) {
            //得到对象
            JSONObject ammeterId = objects.getJSONObject(i);
            ServicePayCreate servicePayCreate = new ServicePayCreate();
            double payPrice = ammeterService.getById(ammeterId).getPayPrice();
            //如果有权限
            boolean flag = adminService.getById(ammeterService.getById(ammeterId).getAdminId()).getPermission() == 1;

            if (!flag || (payPrice < constantService.getById("serverPrice").getV())) {
                double dou = constantService.getById("serverPrice").getV();
                servicePayCreate.setPayPrice(dou);
                BigDecimal bigDecimal = new BigDecimal(dou);
                Double s = Double.parseDouble(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                payALlPrice += s;
            } else {
                servicePayCreate.setPayPrice(payPrice);
                BigDecimal bigDecimal = new BigDecimal(payPrice);
                Double s = Double.parseDouble(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                payALlPrice += s;
            }
            servicePayCreate.setAmmeterId(ammeterId.get("ammeterId").toString());
            servicePayCreate.setServicePayId(date);
            servicePayCreate.setPayType(0);
            servicePayCreate.setCreateTime(new Date());
            servicePayCreateService.save(servicePayCreate);
        }

        ServicePay servicePay = new ServicePay();
        servicePay.setServicePayId(date);
        servicePay.setCreateTime(new Date());

        BigDecimal bigDecimal = new BigDecimal(payALlPrice);
        Double s = Double.parseDouble(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        servicePay.setPayAmount(s);
        servicePay.setPayStatus(0);
        servicePayService.save(servicePay);
        Map<String, Object> mps = new HashMap<>();
        mps.put("no", date);
        mps.put("su", "zkis");
        mps.put("to", s);
        mps.put("bo", " ");

//        model.addAttribute("WIDout_trade_no",date);
//        model.addAttribute("WIDsubject","佐客用电服务2");
//        model.addAttribute("WIDtotal_amount",payALlPrice);
//        model.addAttribute("WIDbody"," ");
//        request.getRequestDispatcher("alipay/alipay.trade.page.pay").forward(request,response);
        return success(mps);
    }

    @RequestMapping("/alipay")
    public String alipay(String no, String su, Double to, String bo, Model model) throws UnsupportedEncodingException {
        model.addAttribute("WIDout_trade_no", no);
        model.addAttribute("WIDsubject", URLDecoder.decode(su, "UTF-8"));
        model.addAttribute("WIDtotal_amount", to);
        model.addAttribute("WIDbody", bo);
        return "alipay/alipay.trade.page.pay";
    }

    @RequestMapping("/managerInfo/Detail")
    public String managerInfoDetail(Model model, String managerId) {
        if (StringUtils.isNotBlank(managerId)) {
            model.addAttribute("managerId", managerId);
        }
        return "managerInfoDetail";
    }


}
